$(function() {
    buttenControl();
    selectList('qryType','30002000');//查询型号类型下拉列表
    selectList('type','30002000');//型号类型下拉列表
    selectList('qryChargeStandard','30029300');//查询充电类型下拉菜单
    selectList('chargestandard','30029300');//充电类型下拉菜单
    SelectVersionName();//新增修改厂商下拉列表
    $('#tb_ads').bootstrapTable({
        method: 'GET',                      //请求方式（*）
        url:projectPath + "/base/equipment/infos/list",
        contentType: 'application/x-www-form-urlencoded',
        toolbar: '#toolbar',                //工具按钮用哪个容器
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
        pagination: true,                   //是否显示分页（*）
        sortable: false,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        search:false,
        queryParams: queryParams,//传递参数（*）
        sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10,20,50],        //可供选择的每页的行数（*）
        strictSearch: true,
        clickToSelect: true,                //是否启用点击选中行
        uniqueId: "id",
        showColumns: true,                  //是否显示所有的列
        showRefresh: true,                  //显示刷新按钮
        showToggle: true,
        minimumCountColumns:2,             //最少允许的列数
        singleSelect:true,
        paginationPreText: "上一页",
        paginationNextText: "下一页",
        columns: [
            {field: 'check', checkbox: true},
            {field: '', title: '序号', align: 'center', formatter: function (value, row, index) {
                var pageSize=$('#tb_ads').bootstrapTable('getOptions').pageSize;//通过表的#id 可以得到每页多少条
                var pageNumber=$('#tb_ads').bootstrapTable('getOptions').pageNumber;//通过表的#id 可以得到当前第几页
                return pageSize * (pageNumber - 1) + index + 1;    //返回每条的序号： 每页条数 * （当前页 - 1 ）+ 序号
            }},
            {field: 'uuid', title: '主键', align: 'center', visible:false},
            {field: 'equipmentname', title: '设备型号',align: 'center',formatter:function (value, row, index) {
                return '<div style="white-space: nowrap;"><a href="javascript:;" onclick="equipment_detail(\''+ row.uuid + '\')">' + value + '</a></div>';
            }},
            {field: 'type', title: '设备类型', align: 'center',formatter:function (value, row, index) {
            var type = '';
                if(value == '1'){
                    type = "直流充电桩";
                }else if(value == '2'){
                    type ="交流充电桩";
                }else if(value == '3'){
                    type ="通用充电桩";
                }else{
                    type ="其他";
                }
                return '<div style="white-space: nowrap;">' + type + '</div>';
            }},
            {field: 'power', title: '额定功率(KW)', align: 'center',formatter:function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'minoutvolt', title: '最小输出电压(V)', align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'maxoutvolt', title: '最大输出电压(V)', align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'minoutcurrent', title: '最小输出电流(A)',align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'maxoutcurrent', title: '最大输出电流(A)',align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value = "";
                };
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'vendorName', title: '生产厂商',align: 'center',formatter:function (value, row, index) {
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }},
            {field: 'chargestandard', title: '充电标准',align: 'center',formatter:function (value, row, index) {
            var type = '';
                if(value == "01"){
                    type = "国标";
                }else if(value == "02"){
                    type = "美标";
                }else if(value == "03"){
                    type = "欧标";
                }else if(value == "04"){
                    type = "国标2015";
                }else{
                    type = "其他";
                };
                return "<div style='white-space: nowrap;'>" + type + "</div>";
            }},
            {field: 'createdat', title: '创建时间',align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                }
                return "<div style='width:150px;min-width: 150px;max-width: 150px;margin: auto;'>" + value + "</div>";
            }},
            {field: 'updatedat', title: '修改时间',align: 'center',formatter:function (value, row, index) {
                if(value == "" || value == null){
                    value="";
                }else{
                    value = getLocalTime(value);
                }
                return "<div style='white-space: nowrap;'>" + value + "</div>";
            }}
        ],
        responseHandler: function (obj) {
            return {
                total:obj.data.total,
                rows:obj.data.list
            }
        }
    });
    // 查询
    $("#btnQuery").click(function(){
        $('#tb_ads').bootstrapTable('refresh', {url:projectPath + "/base/equipment/infos/list",pageNumber:1});
    });
    //清空
    $("#btnEmpty").click(function () {
        $("#updatedatStat").val("");
        $("#updatedatEnd").val("");
        $("#createdatStat").val("");
        $("#createdatEnd").val("");
        $("#qryChargeStandard").val("");
        $("#qryEquipmentName").val("");
        $("#qryType").val("");
    });
    submitVerification();
});
$("#equipmentName,#vendoruuid").change(function (){
    if($("#equipmentName").val() != "") {
        $.ajax({
            type: 'POST',
            url: projectPath + '/base/equipment/infos/qryEquipmentInfoCountByName',
            //async:false,
            data: {name: $("#equipmentName").val(), vendorUuid: $("#vendoruuid").val()},
            dataType: 'json',
            success: function (data) {
                if (data.data != 0) {
                    layerAlert.warnMessage("厂商下类型名称已存在，请重新填写！");
                    $("#equipmentName").val("");
                    return false;
                };
            },
            error: function () {
                layerAlert.errorMessage("数据错误！");
            }
        });
    }
});

function queryParams() {
    var filterinfo = {};
    if($("#qryType").val() !=""){
        filterinfo.type = $("#qryType").val();
    };
    if($("#vendoruuidQuery").val() != ""){
        filterinfo.vendoruuid = $("#vendoruuidQuery").val();
    };
    if($("#qryEquipmentName").val() !=""){
        filterinfo.equipmentName = $("#qryEquipmentName").val();
    }
    if($("#qryChargeStandard").val() !=""){
        filterinfo.chargeStandard = $("#qryChargeStandard").val();
    };
    if($("#createdatStat").val() !=""){
        filterinfo.createdAtStat = $("#createdatStat").val();
    };
    if($("#createdatEnd").val() !=""){
        filterinfo.createdAtEnd = $("#createdatEnd").val();
    };
    if($("#updatedatStat").val() !=""){
        filterinfo.updatedAtStat = $("#updatedatStat").val();
    };
    if($("#updatedatEnd").val() !=""){
        filterinfo.updatedAtEnd = $("#updatedatEnd").val();
    };
    filterinfo.offset = (this.pageNumber-1)*this.pageSize;
    filterinfo.limit = this.pageSize;
    return filterinfo;
};


//创建开始时间
$('#createdatStat').datetimepicker({
    language:  'zh-CN',
    format: 'yyyy-mm-dd',
    weekStart: 1,
    autoclose: 1,
    todayBtn: 1,
    initialDate:new Date(),
    startView: 2,
    minView: 2,
    forceParse: 0,
    pickerPosition:'bottom-right',
}).on("changeDate",function(e){
    if(e.date != null&&e.date != ''){
        var createdatStat = Dateinit.getNextDay(e.date); //2018-03-10 14:47
    }
    //前一天与后一天时间的比较清空
    var start2 = new Date(Date.parse($('#createdatStat').val().replace(/-/g,"/"))); // 中国标准时间
    if(Date.parse(createdatStat.replace(/-/g,"/"))> start2){
        $("#createdatEnd").val('');
    }
    //设置结束时间的起始值未开始时间的下一天
    $("#createdatEnd").datetimepicker("setStartDate",createdatStat);
});
//创建结束时间
$('#createdatEnd').datetimepicker({
    language:  'zh-CN',
    format: 'yyyy-mm-dd',
    weekStart: 1,
    autoclose: 1,
    todayBtn: 1,
    startView: 2,
    minView: 2,
    forceParse: 0,
    pickerPosition:'bottom-right',
});
//修改开始时间
$('#updatedatStat').datetimepicker({
    language:  'zh-CN',
    format: 'yyyy-mm-dd',
    weekStart: 1,
    autoclose: 1,
    todayBtn: 1,
    initialDate:new Date(),
    startView: 2,
    minView: 2,
    forceParse: 0,
    pickerPosition:'bottom-right',
}).on("changeDate",function(e){
    if(e.date != null&&e.date != ''){
        var updatedatStat = Dateinit.getNextDay(e.date); //2018-03-10 14:47
    }
    //前一天与后一天时间的比较清空
    var start2 = new Date(Date.parse($('#updatedatStat').val().replace(/-/g,"/"))); // 中国标准时间
    if(Date.parse(updatedatStat.replace(/-/g,"/"))> start2){
        $("#updatedatEnd").val('');
    }
    //设置结束时间的起始值未开始时间的下一天
    $("#updatedatEnd").datetimepicker("setStartDate",updatedatStat);
});
//修改结束时间
$('#updatedatEnd').datetimepicker({
    language:  'zh-CN',
    format: 'yyyy-mm-dd',
    weekStart: 1,
    autoclose: 1,
    todayBtn: 1,
    startView: 2,
    minView: 2,
    forceParse: 0,
    pickerPosition:'bottom-right',
});

// 新增
$("#btnAdd").on("click",function () {
    submitVerification();
    $(".addEquipment select,input").prop("disabled",false);
    $("#equipmentName").prop('readnoly',false);
    var index = layer.open({
        type: 1,
        title: "新增设备型号",
        shadeClose: true,
        shade: 0.3,
        move :false,
        area: ['90%', '100%'],
        skin: 'layui-layer-rims',
        content: $(".addEquipment"),
        closeBtn:1,
        shadeClose:false,
        btn:['确定','取消'],
        yes:function () {
            var bootstrapValidator = $(".bootstrapValidators").data('bootstrapValidator');
            bootstrapValidator.validate();
            if(!bootstrapValidator.isValid()){
                return ;
            };
            var param =  Params();
            $.ajax({
                type: 'POST',
                url: projectPath + '/base/equipment/infos/insert',
                data: param,
                dataType: 'json',
                success: function (r) {
                    if(r.code == "0"){
                        layerAlert.successMessage("添加成功","");
                    }else{
                        layerAlert.errorMessage("添加失败");
                    };
                },
                error:function () {
                    layerAlert.errorMessage("网络异常");
                }
            });
            $(".addEquipment select,input").val("");
            submitVerification();
            $(".bootstrapValidators").data('bootstrapValidator').destroy();
            $('.bootstrapValidators').data('bootstrapValidator', null);
        },
        btn2:function () {
            submitVerification();
            $(".bootstrapValidators").data('bootstrapValidator').destroy();
            $('.bootstrapValidators').data('bootstrapValidator', null);
            $(".addEquipment select,input").val("");
        },
        cancel:function(){
            submitVerification();
            $(".bootstrapValidators").data('bootstrapValidator').destroy();
            $('.bootstrapValidators').data('bootstrapValidator', null);
            $(".addEquipment select,input").val("");
        }
    });

});



//新增修改传入参数zhangYiHang 2018.3.22
function Params() {
    var filterinfo = {};
    filterinfo.uuid = $("#uuid").val();
    filterinfo.type = $("#type").val();
    filterinfo.equipmentNo = $("#equipmentNo").val();
    filterinfo.equipmentName = $("#equipmentName").val();
    filterinfo.chargeStandard = $("#chargestandard").val();
    filterinfo.vendorUuid = $("#vendoruuid").val();
    filterinfo.power = $("#power").val();
    filterinfo.minOutVolt = $("#minoutvolt").val();
    filterinfo.maxOutVolt = $("#maxoutvolt").val();
    filterinfo.maxOutCurrent = $("#maxoutcurrent").val();
    filterinfo.minOutCurrent = $("#minoutcurrent").val();
    return filterinfo;
};


// 修改
$("#brnRevise").click(function(){
    submitVerification();
    $(".addEquipment select,input").prop("disabled",false);
    $("#equipmentName").prop('readnoly',false);
    var ids = getSelectedDeleteParams();
    if (ids != '' && ids != null) {
        var index = layer.open({
            type: 1,
            title: "修改设备型号",
            shadeClose: true,
            shade: 0.3,
            move :false,
            area: ['90%', '100%'],
            skin: 'layui-layer-rims',
            content: $(".addEquipment"),
            closeBtn:1,
            shadeClose:false,
            btn:['确定','取消'],
            success:function(){
                equipment_detail_huixian(ids);
            },
            yes:function () {
                var bootstrapValidator = $(".bootstrapValidators").data('bootstrapValidator');
                bootstrapValidator.validate();
                if(!bootstrapValidator.isValid()){
                    return ;
                };
                var param =  Params();
                $.ajax({
                    type: 'POST',
                    url: projectPath + '/base/equipment/infos/update',
                    data: param,
                    dataType: 'json',
                    success: function (r) {
                        if(r.code == "0"){
                            layerAlert.successMessage("修改成功","");
                        }else{
                            layerAlert.errorMessage("修改失败");
                        };
                    },
                    error:function () {
                        layerAlert.errorMessage("网络异常");
                    }
                });

                submitVerification();
                $(".bootstrapValidators").data('bootstrapValidator').destroy();
                $('.bootstrapValidators').data('bootstrapValidator', null);
                $(".addEquipment select,input").val("");
                $(".addEquipment select,input").prop("disabled",false);
            },
            btn2:function () {
                submitVerification();
                $(".bootstrapValidators").data('bootstrapValidator').destroy();
                $('.bootstrapValidators').data('bootstrapValidator', null);
                $(".addEquipment select,input").val("");
                $(".addEquipment select,input").prop("disabled",false);
            },
            cancel:function(){
                submitVerification();
                $(".bootstrapValidators").data('bootstrapValidator').destroy();
                $('.bootstrapValidators').data('bootstrapValidator', null);
                $(".addEquipment select,input").val("");
                $(".addEquipment select,input").prop("disabled",false);
            }
        });
    } else {
        layerAlert.errorMessage("您的选择为空");
    }
});

// 详情
function equipment_detail(id){
    $(".addEquipment select,input").prop("disabled",true);
    $("#equipmentName").prop('readnoly',true);
    var index = layer.open({
        type: 1,
        title: "设备型号详情",
        shadeClose: true,
        shade: 0.3,
        move :false,
        area: ['90%', '80%'],
        skin: 'layui-layer-rims',
        content: $(".addEquipment"),
        closeBtn:1,
        btn:['关闭'],
        shadeClose:false,
        success:function(){
            equipment_detail_huixian(id);
        },
        yes:function(){
            layer.close(index);
            $(".addEquipment select,input").val("");
            $(".addEquipment select,input").prop("disabled",false);
        },
        cancel:function(){
            $(".addEquipment select,input").val("");
            $(".addEquipment select,input").prop("disabled",false);
        }
    });
}
// 详情查看与修改回显公共方法
function equipment_detail_huixian(id){
    $.ajax({
        url: projectPath + '/base/equipment/infos/detail?id=' + id,
        type: 'POST',
        dataType: 'json',
        success:function(result){
            data = result.data;
            $("#equipmentNo").val(data.equipmentno); // 型号编号
            $("#uuid").val(id);
            $("#type").val(data.type); //型号类型
            $("#chargestandard").val(data.chargestandard); // 国家标准
            $("#vendoruuid").val(data.vendoruuid); // 生产厂商
            $("#power").val(data.power);// 额定功率
            $("#equipmentName").val(data.equipmentname);
            $("#minoutvolt").val(data.minoutvolt); // 最小输出电压
            $("#maxoutvolt").val(data.maxoutvolt); // 最大输出电压
            $("#maxoutcurrent").val(data.maxoutcurrent); // 最大输出电流
            $("#minoutcurrent").val(data.minoutcurrent); // 最小输出电流
        },
        error:function(){
            layerAlert.errorMessage("网络异常");
        }
    });
}
//删除按钮
$("#btnDelete").on("click",function(){
    var ids = getSelectedDeleteParams();
    if (ids != '' && ids != null) {
        layerAlert.confirmMessage("确定要删除?",projectPath + "/base/equipment/infos/del?id="+ids, function(data){
            if(data.data > 0){
                layerAlert.successMessage("操作成功","");
            } else if (data.data < 0){
                layerAlert.warnMessage("型号已绑定桩不能删除!绑定数为"+ data.data * (-1));
            } else if (data.data == 0){
                layerAlert.errorMessage("删除失败!")
            } else{
                layerAlert.errorMessage("出错了");
            };
        });
    }else{
        layerAlert.errorMessage("您的选择为空");
    }
});

//动态下拉列表zhangYiHang 2018.3.22
function selectList(id,code) {
    $.get(projectPath + '/base/constss/list?code='+code, function (r) {
        var data = r.data;
        var value = '<option value="">--请选择--</option>';
        $(data).each(function(index,r){
            value += '<option value="'+r.constvalue+'">'+r.constname+'</option>';
        })
        $("#" + id).append(value);
    });
};
//厂商下拉列表展示zhangYiHang 2018.3.22
function SelectVersionName() {
    $.get(projectPath + "/base/vendor/infos/list", function (r) {
        var data = r.data.list;
        var value = '<option value="">--请选择--</option>';
        $(data).each(function(index,r){
            value += '<option value="'+r.uuid+'">'+r.name+'</option>';
        })
        $(".vendor").append(value);
    });
}

// 新增修改提交验证
function submitVerification(){
    $(".bootstrapValidators").bootstrapValidator({
        message: 'This value is not valid',
        feedbackIcons: {
            //valid: 'glyphicon glyphicon-ok',
            //invalid: 'glyphicon glyphicon-remove',
            //validating: 'glyphicon glyphicon-refresh'
        },
        fields:{
            equipmentName:{
                validators:{
                    notEmpty: {
                        message: '类型名称不能为空'
                    },
                },
            },
            type:{
                validators:{
                    notEmpty: {
                        message: '型号类型不能为空'
                    },
                },
            },
            chargestandard:{
                validators:{
                    notEmpty: {
                        message: '充电标准不能为空'
                    },
                },
            },
            vendoruuid:{
                validators:{
                    notEmpty:{
                        message:"生产厂商不能为空"
                    }
                }
            },
            minoutvolt: {
                validators: {
                    notEmpty: {
                        message: '最小输出电压不能为空'
                    },
                    regexp: {
                        regexp: /^\d+(\.\d+)?$/,
                        message: '最小输出电压不能小于等于0 '
                    },
                    callback: {
                        message: '最小输出电压不能大于最大输出电压',
                        callback:function(value, validator,$field){
                            var maxoutvolt = validator.getFieldElements("maxoutvolt").val();///获得另一个的值
                            if(maxoutvolt =="" ){
                                return true;
                            };
                            if("maxoutvolt" == "minoutvolt"){
                                if (parseInt(maxoutvolt)<parseInt(value)) {
                                    //当前文本框满足条件，"maxoutvolt"的文本框也满足条件，更新"maxoutvolt"文本框的状态；
                                    validator.updateStatus("maxoutvolt", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }else{
                                if (parseInt(maxoutvolt)>parseInt(value)) {
                                    //当前文本框满足条件，"maxoutvolt"的文本框也满足条件，更新"maxoutvolt"文本框的状态；
                                    validator.updateStatus("maxoutvolt", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }
                            return false;
                        }
                    }
                }
            },
            maxoutvolt: {
                validators: {
                    notEmpty: {
                        message: '最大输出电压不能为空'
                    },
                    regexp: {
                        regexp: /^\d+(\.\d+)?$/,
                        message: '最大输出电压不能小于等于0 '
                    },
                    callback: {
                        message:'最大输出电压不能小于最小输出电压',
                        callback: function (value, validator, $field) {
                            var minoutvolt = validator.getFieldElements("minoutvolt").val();
                            if(minoutvolt =="" ){
                                return true;
                            };
                            if("minoutvolt" == "maxoutvolt"){
                                if (parseInt(minoutvolt)>parseInt(value)) {
                                    validator.updateStatus("minoutvolt", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }else{
                                if (parseInt(minoutvolt)<parseInt(value)) {
                                    validator.updateStatus("minoutvolt", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }
                            return false;
                        }
                    }
                }
            },
            minoutcurrent: {
                validators: {
                    notEmpty: {
                        message: '最小输出电流不能为空'
                    },
                    regexp: {
                        regexp: /^\d+(\.\d+)?$/,
                        message: '最小输出电流不能小于等于0 '
                    },
                    callback: {
                        message:'最小输出电流不能小大于最大输出电流',
                        callback:function(value, validator,$field){
                            var maxoutcurrent = validator.getFieldElements("maxoutcurrent").val();
                            if(maxoutcurrent =="" ){
                                return true;
                            };
                            if("maxoutcurrent" == "minoutcurrent"){
                                if (parseInt(maxoutcurrent)<parseInt(value)) {
                                    validator.updateStatus("maxoutcurrent", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }else{
                                if (parseInt(maxoutcurrent)>parseInt(value)) {
                                    validator.updateStatus("maxoutcurrent", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }
                            return false;
                        }
                    }
                }
            },
            maxoutcurrent: {
                validators: {
                    notEmpty: {
                        message: '最大输出电流不能为空'
                    },
                    regexp: {
                        regexp: /^\d+(\.\d+)?$/,
                        message: '最大输出电流不能小于等于0 '
                    },
                    callback: {
                        message:'最大输出电流不能小于最小输出电流',
                        callback: function (value, validator, $field) {
                            var minoutcurrent = validator.getFieldElements("minoutcurrent").val();
                            if(minoutcurrent =="" ){
                                return true;
                            };
                            if("minoutcurrent" == "maxoutcurrent"){
                                if (parseInt(minoutcurrent)>parseInt(value)) {
                                    validator.updateStatus("minoutcurrent", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }else{
                                if (parseInt(minoutcurrent)<parseInt(value)) {
                                    validator.updateStatus("minoutcurrent", validator.STATUS_VALID, 'callback');
                                    return true;
                                }
                            }
                            return false;
                        }
                    }
                }
            },
            power: {
                validators: {
                    notEmpty: {
                        message: '额定功率不能为空'
                    },
                    regexp: {
                        regexp: /^\d+(\.\d+)?$/,
                        message: '额定功率不能小于等于0 '
                    }
                }
            },
        }
    });
};

/**
 * zhangYiHang 18.3.20
 * 页面按钮控制
 * @constructor
 */
function buttenControl() {
    var urls = paramUrlByButten();
    if(urls.length>0){
        for (var i in urls){
            if('update' == urls[i]){
                $("#brnRevise").show();
            } else if('insert' == urls[i]){
                $("#btnAdd").show();
            }else if('delete' == urls[i]){
                $("#btnDelete").show()
            }else if('updatePassword' == urls[i]){
                $("#btnRevisePass").show()
            }
        }
    }
}